package LeetCode;

public class Code148_sortList {

    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        // 此时slow在中点
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(tmp);
        // merge
        ListNode h = new ListNode(0);
        ListNode dummy = h;
        while (l1 != null && l2 != null){
            if (l1.val <= l2.val){
                h.next = l1;
                l1 = l1.next;
            } else {
                h.next = l2;
                l2 = l2.next;
            }
            h = h.next;
        }
        if (l1 != null){
            h.next = l1;
        }
        if (l2 != null){
            h.next = l2;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode l = new ListNode(4);
        l.next = new ListNode(2);
        l.next.next = new ListNode(1);
        l.next.next.next = new ListNode(3);
        System.out.println(sortList(l).val);
    }
}
